const encoding = require('encoding.js') // 处理全中文字符

// 文本字符串转buffer
const str2ab = (str) => {
  if (str != '') {
    return new encoding.TextEncoder("gb2312", {
      NONSTANDARD_allowLegacyEncoding: true
    }).encode(str).buffer
  } else {
    return false
  }
}
// 文字
function textSend(e) {
  let tempCode = 'CLS' + '\r\n' // CLS(清除缓存)
  tempCode += 'SIZE 812dot,403dot' + '\r\n' // 增加高度以容纳所有内容
  tempCode += 'GAP 2,0' + '\r\n' // 设置标签间隙
  let yPosition = 20; // 起始Y坐标
  const lineHeight = 30; // 行高
  console.log(e,"eeeeeeeeeeeee")
  // 遍历对象的所有属性
  Object.keys(e).forEach(key => {
    // if (e[key]) { // 只打印有值的属性
      const text = `${key}: ${e[key]}`;
      tempCode += `TEXT 100,${yPosition},"TSS24.BF2",0,1,1,"${text}"` + '\r\n';
      yPosition += lineHeight; // 每行递增Y坐标
    // }
  });
  tempCode += 'PRINT 1,1' + '\r\n' // PRINT(打印) (份数) (每份张数)
  return str2ab(tempCode)
}

function autoWrapTextBetter(text, maxBytesPerLine = 40) {
  const lines = [];
  let currentLine = '';
  let currentBytes = 0;
  
  for (let char of text) {
    const charBytes = getCharBytes(char);
    
    // 如果加上这个字符会超出行限制
    if (currentBytes + charBytes > maxBytesPerLine) {
      lines.push(currentLine);
      currentLine = char;
      currentBytes = charBytes;
    } else {
      currentLine += char;
      currentBytes += charBytes;
    }
  }
  
  if (currentLine) {
    lines.push(currentLine);
  }
  
  return lines;
}

function getCharBytes(char) {
  // 中文字符算2个字节，英文算1个
  return char.charCodeAt(0) > 255 ? 2 : 1;
}

function printWrappedTextBetter(text, x, startY, lineHeight = 30) {
  let tempCode = '';
  const lines = autoWrapTextBetter(text, 36); // 每行约18个汉字或36个英文
  
  lines.forEach((line, index) => {
    const y = startY + (index * lineHeight);
    tempCode += `TEXT ${x},${y},"TSS24.BF2",0,1,1,"${line}"\r\n`;
  });
  
  return { code: tempCode, lineCount: lines.length };
}


function printQuickWrap(text, x, startY) {
  let tempCode = '';
  const lines = text.match(/.{1,16}/g) || []; // 每行16字符
  
  lines.forEach((line, i) => {
    tempCode += `TEXT ${x},${startY + i * 30},"TSS24.BF2",0,1,1,"${line}"\r\n`;
  });
  
  return tempCode;
}


// 产品综合信息
function textchanpin(tmp1) {
  let tempCode = 'CLS' + '\r\n'
  tempCode += 'SIZE 812dot,803dot' + '\r\n' // 增加高度以容纳所有内容
  tempCode += 'GAP 2,0' + '\r\n'
  tempCode += 'DENSITY 6\r\n';
  const lineHeight = 30; // 行高
  // ====== 第一、二行文字 ======
  console.log(tmp1,"==========tmp1tmp1tmp1tmp1tmp1")
  tempCode += `TEXT 150,20,"TSS24.BF2",0,1,1,"产品型号: ${tmp1.产品型号}"` + '\r\n'
  tempCode += `TEXT 150,50,"TSS24.BF2",0,1,1,"生产日期: ${tmp1.生产日期}"` + '\r\n'
  tempCode += `BARCODE 150,80,"128",80,1,0,2,4,"${tmp1.产品条码}"` + '\r\n'
  let tmp10 = "产品信息"+tmp1.产品信息
  tempCode += printQuickWrap(`${tmp10}`, 150, 170);
  tempCode += 'PRINT 1,1' + '\r\n'
  console.log("优化版打印指令:", tempCode);
  return str2ab(tempCode);

}

// 条码
//tmp={上方添加文字说明,条形码格式,添加文字说明}
function barcodeSend(tmp) {
  let tempCode = 'CLS' + '\r\n'
  tempCode += 'SIZE 812dot,403dot' + '\r\n'
  tempCode += 'GAP 2,0' + '\r\n'
  tempCode += 'DIRECTION 1' + '\r\n'
  // 在条形码上方添加文字说明
  tempCode += `TEXT 200,100,"TSS24.BF2",0,1,1,"产品型号:${tmp.产品型号}"` + '\r\n'
  // 使用CODE128码，这是最通用的条形码格式
  tempCode += `BARCODE 150,140,"128",80,1,0,2,4,"${tmp.产品条码}"` + '\r\n'
  // 在条形码下方添加文字说明
  tempCode += `TEXT 200,250,"TSS24.BF2",0,1,1,"${tmp.产品信息}"` + '\r\n'
  tempCode += 'PRINT 1,1' + '\r\n'
  console.log("CODE128指令:", tempCode);
  return str2ab(tempCode);
}

// 二维码
function qrcodeSend() {
  let tempCode = 'CLS' + '\r\n' // CLS(清除缓存)
  tempCode += 'SIZE 812dot,203dot' + '\r\n' // SIZE(设置标签大小) (宽度dot,高度dot)
  // tempCode += 'QRCODE 10,20,Q,5,A,0,' // QRCODE(绘制QR二维码) (起始位置x坐标) (起始位置y坐标) (纠错等级L-M-Q-H) (码宽度) (自动编码A-M) (顺时针0度)
  tempCode += 'QRCODE 250,100,Q,5,A,0,' // 从10,20调整为100,50
  tempCode += '"https://www.baidu.com/index.php?tn=75144485_4_dg&ch=1"' + '\r\n' // 条形码内容
  tempCode += 'PRINT 1,1' + '\r\n' // PRINT(打印) (份数) (每份张数)
  return str2ab(tempCode)
}

// 样表
function tableSend() {
  let tempCode = 'CLS' + '\r\n'
  tempCode += 'SIZE 812dot,800dot' + '\r\n'
  tempCode += 'TEXT 90,90, "TSS24.BF2",0,1,1,"沾危废包装物及物品"' + '\r\n'
  tempCode += 'TEXT 90,135,"TSS24.BF2", 0,1,1,"HW49其他废物"' + '\r\n'
  tempCode += 'TEXT 90,180,"TSS24.BF2",0,1,1,"900-041-49"' + '\r\n'
  tempCode += 'TEXT 390,180,"TSS24.BF2",0,1,1,"固态"' + '\r\n'
  tempCode += 'TEXT 90,210,"TSS24.BF2",0,1,1,"有机物-化学成分"' + '\r\n'
  tempCode += 'TEXT 90,300,"TSS24.BF2",0, 1,1,"有机物-危险成分"' + '\r\n'
  tempCode += 'TEXT 90,390,"TSS24.BF2",0, 1,1,"佩戴防护劳动用品"' + '\r\n'
  tempCode += 'TEXT 90,480,"TSS24.BF2",0,1,1,"12345678900987654321asdfgh0000099998"' + '\r\n'
  tempCode += 'TEXT 90,525,"TSS24.BF2",0,1,1,"某省某市某区某有限公司"' + '\r\n'
  tempCode += 'TEXT 90,570,"TSS24.BF2",0,1,1,"某省某市某区某有限公司"' + '\r\n'
  tempCode += 'TEXT 90,615,"TSS24.BF2",0,1,1,"张三/13800138000"' + '\r\n'
  tempCode += 'TEXT 90,660,"TSS24.BF2",0,1,1,"2020-02-02"' + '\r\n'
  tempCode += 'TEXT 390,660,"TSS24.BF2",0,1,1,"1吨"' + '\r\n'
  tempCode += 'TEXT 90,705,"TSS24.BF2",0,1,1,"测试"' + '\r\n'
  tempCode += 'TEXT 700,390,"TSS24.BF2",0,1,1,"√"' + '\r\n'
  tempCode += 'QRCODE 585,500,Q,7,A,0,"http://dascom.cn/front/web/"' + '\r\n'
  tempCode += 'PRINT 1,1' + '\r\n'
  return str2ab(tempCode)
}

// 通知
function notifySend() {
  return new Uint8Array([27, 13, 83, 27, 136, 1, 27, 16, 69]).buffer // 握手指令(1B 0D 53 1B 88 01 1B 10 45)
}

// 图片
function imageSend(image) {
  let img = bitmap(image)
  let tempCode = 'CLS' + '\r\n' // CLS(清除缓存)
  tempCode += 'SIZE 812dot,203dot' + '\r\n' // SIZE(设置标签大小) (宽度dot,高度dot)
  tempCode += 'BITMAP 10,20,' + img.width / 8 + ',' + img.height + ',0,' // BITMAP(绘制QR二维码) (起始位置x坐标) (起始位置y坐标) (宽度byte) (高度dot) (绘制模式0-1-2)
  return concate(str2ab(tempCode), img.imageData, str2ab('\r\n' + 'PRINT 1,1' + '\r\n')) // PRINT(打印) (份数) (每份张数)
}

// 多个Arraybuffer合并
const concate = (...arrays) => {
  let str = ''
  for (let arr of arrays) {
    str += String.fromCharCode.apply(null, new Uint8Array(arr))
  }
  var buf = new ArrayBuffer(str.length)
  var bufView = new Uint8Array(buf)
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i)
  }
  return bufView.buffer
}

// 图片处理
const bitmap = (data) => {
  let pix = data.imageData
  let sendWidth = data.width
  let sendHeight = data.height
  let sendImageData = []
  let part = []
  let index = 0
  pix = pix.data
  console.log('pix======', pix)
  // 转黑白数组
  for (let i = 0; i < pix.length; i += 4) {
    let grayPixle1 = grayPixle(pix.slice(i, i + 4))

    part[index] = grayPixle1 > 180 ? 1 : 0
    index++
  }
  console.log('part=====', part)
  // 转位图数据
  for (let j = 0; j * 8 < part.length; j++) {
    let temp = j * 8;
    sendImageData[j] = part[temp] + "" + part[temp + 1] + "" + part[temp + 2] + "" + part[temp + 3] + "" + part[temp + 4] + "" + part[temp + 5] + "" + part[temp + 6] + "" + part[temp + 7]
    sendImageData[j] = parseInt(sendImageData[j], 2)
  }
  console.log('sendImageData=====', sendImageData)
  return {
    imageData: sendImageData,
    width: sendWidth,
    height: sendHeight
  }

  function grayPixle(pix) {
    return pix[0] * 0.299 + pix[1] * 0.587 + pix[2] * 0.114
  }
}
module.exports = {
  textSend: textSend,
  barcodeSend: barcodeSend,
  qrcodeSend: qrcodeSend,
  tableSend: tableSend,
  notifySend: notifySend,
  textchanpin:textchanpin,
  imageSend: imageSend
}